<?php
namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Pay extends Home
{

    protected $noNeedLogin = ['business', 'subject'];

    // 控制器初始化
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->PayModel = model('Pay.Pay');
        $this->RecordModel = model('Business.Record');
        $this->SubjectModel = model('Subject.Subject');
        $this->OrderModel = model('Subject.Order');
        $this->ReceiveModel = model('Coupon.Receive');
        $this->CommissionModel = model('Business.Commission');
    }

    // 用户充值
    public function business()
    {
        if ($this->request->isPost())
        {
            // 支付订单id
            $payid = $this->request->param('id', 0, 'trim');

            $pay = $this->PayModel->find($payid);

            if (!$pay)
            {
                return json(['code' => 0, 'msg' => '支付订单不存在', 'data' => null]);
            }

            // 充值的金额
            $total = isset($pay['total']) ? $pay['total'] : 0;
            $total = floatval($total);

            // 第三方参数(可多参数)
            $third = isset($pay['third']) ? $pay['third'] : '';

            // json字符串转换数组
            $third = json_decode($third, true);

            // 从数组获取充值的用户id
            $busid = isset($third['busid']) ? $third['busid'] : 0;

            // 支付方式
            $type = isset($pay['type']) ? $pay['type'] : 'zfb';
            $payment = $type == "zfb" ? "支付宝" : "微信支付";

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business)
            {
                return json(['code' => 0, 'msg' => '充值用户不存在', 'data' => null]);
            }

            //判断充值金额
            if ($total <= 0)
            {
                return json(['code' => 0, 'msg' => '充值金额不能为0', 'data' => null]);
            }

            // 开启事务
            $this->BusinessModel->startTrans();
            $this->RecordModel->startTrans();

            // 余额 + 充值的金额
            $money = bcadd($business['money'], $total, 2);

            $BusinessData = [
                'id' => $business['id'],
                'money' => $money
            ];

            $validate = [
                [
                    'money' => ['number', 'egt:0'],
                ],
                [
                    'money.number'  => '余额必须是数字类型',
                    'money.egt'      => '余额必须大于等于0元',
                ]
            ];

            // 用户表更新
            $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

            if ($BusinessStatus === false)
            {
                return json(['code' => 0, 'msg' => $this->BusinessModel->getError(), 'data' => null]);
            }

            $RecordData = [
                'total' => $total,
                'busid' => $business['id'],
                'content' => "{$payment}充值了￥{$total}元"
            ];

            // 消费记录表新增
            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
            if ($RecordStatus === false)
            {
                $this->BusinessModel->rollback();
                return json(['code' => 0, 'msg' => $this->RecordModel->getError(), 'data' => null]);
            }

            if ($BusinessStatus === FALSE || $RecordStatus === FALSE)
            {
                $this->RecordModel->rollback();
                $this->BusinessModel->rollback();
                return json(['code' => 0, 'msg' => '充值失败', 'data' => null]);
            }
            else
            {
                $this->BusinessModel->commit();
                $this->RecordModel->commit();
                return json(['code' => 1, 'msg' => '充值成功', 'data' => null]);
            }
        }
    }

    
    // 课程购买
    public function subject()
    {
        if ($this->request->isPost())
        {
            // 支付订单id
            $payid = $this->request->param('id', 19, 'trim');

            $pay = $this->PayModel->find($payid);

            if (!$pay)
            {
                return json(['code' => 0, 'msg' => '支付订单不存在', 'data' => null]);
            }

            // 充值的金额
            $total = isset($pay['total']) ? $pay['total'] : 0;
            $total = floatval($total);

            // 第三方参数(可多参数)
            $third = isset($pay['third']) ? $pay['third'] : '';

            // json字符串转换数组
            $third = json_decode($third, true);

            // 从数组获取充值的用户id
            $busid = isset($third['busid']) ? $third['busid'] : 0;
            $subid = isset($third['subid']) ? $third['subid'] : 0;
            $couid = isset($third['couid']) ? $third['couid'] : 0;

            // 支付方式
            $type = isset($pay['type']) ? $pay['type'] : 'zfb';
            $payment = $type == "zfb" ? "支付宝" : "微信支付";

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business)
            {
                return json(['code' => 0, 'msg' => '充值用户不存在', 'data' => null]);
            }

            //判断课程是否存在
            $subject = $this->SubjectModel->find($subid);

            if (!$subject)
            {
                return json(['code' => 0, 'msg' => '课程不存在', 'data' => null]);
            }

            //开启事务逻辑
            $this->OrderModel->startTrans();
            $this->RecordModel->startTrans();
            $this->ReceiveModel->startTrans();
            $this->CommissionModel->startTrans();

            $OrderData = [
                'subid' => $subid,
                'busid' => $busid,
                'total' => $total,
                'code' => build_code('SUB'),
                'pay' => $pay['type'],
            ];

            //订单表 校验器
            $OrderStatus = $this->OrderModel->save($OrderData);

            if ($OrderStatus === false)
            {
                return json(['code' => 0, 'msg' => $this->OrderModel->getError(), 'data' => null]);
            }

            //消费记录
            $paytext = $pay['type_text'];
            $RecordData = [
                'total' => "-{$total}",
                'busid' => $busid,
                'content' => "购买了[{$subject['title']}]课程,花费了￥{$total}元 （{$paytext}）"
            ];

            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            if ($RecordStatus === false)
            {
                $this->OrderModel->rollback();
                return json(['code' => 0, 'msg' => $this->RecordModel->getError(), 'data' => null]);
            }

            //查询是否有选择优惠券
            $where = ['receive.id' => $couid, 'receive.status' => '1'];
            $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->find();

            //如果有选择优惠券那么就要更新优惠券使用状态
            if ($coupon)
            {
                $CouponReceiveData = [
                    'id' => $couid,
                    'status' => '0'
                ];

                $CouponReceiveStatus =  $this->ReceiveModel->isUpdate(true)->save($CouponReceiveData);
                if ($CouponReceiveStatus === false)
                {
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    return json(['code' => 0, 'msg' => '优惠券状态更新失败', 'data' => null]);
                }
            }

            //判断是否有推荐人可以得到佣金
            $parentid = $business['parentid'] ? trim($business['parentid']) : 0;
            $parent = $this->BusinessModel->find($parentid);

            if ($parent)
            {
                //佣金比率
                $AmountRate = config('site.AmountRate') ? config('site.AmountRate') : 0.05;

                //消费金额*佣金比率 = 转给推荐人
                $amount = bcmul($total, $AmountRate, 2);

                $CommissionData = [
                    'orderid' => $this->OrderModel->id,   //获取插入最后一条的自增ID
                    'busid' => $busid,
                    'parentid' => $parentid,
                    'amount' => $amount,
                    'type' => 'subject', //买课程
                    'status' => '0' //未提现
                ];

                // 验证器
                $CommissionStatus = $this->CommissionModel->save($CommissionData);
                if ($CommissionStatus === false)
                {
                    $this->OrderModel->rollback();
                    $this->RecordModel->rollback();
                    $this->ReceiveModel->rollback();
                    return json(['code' => 0, 'msg' => '推荐信息存储失败', 'data' => null]);
                }
            }

            if ($OrderStatus === FALSE || $RecordStatus === FALSE)
            {
                $this->CommissionModel->rollback();
                $this->ReceiveModel->rollback();
                $this->RecordModel->rollback();
                $this->OrderModel->rollback();
                return json(['code' => 0, 'msg' => '购买课程失败', 'data' => null]);
            }
            else
            {
                $this->OrderModel->commit();
                $this->RecordModel->commit();
                $this->ReceiveModel->commit();
                $this->CommissionModel->commit();
                return json(['code' => 1, 'msg' => '购买课程成功', 'data' => null]);
            }
        }
    }
}